package com.mjk.common.util;

import com.mjk.common.tools.logger.BizLogger;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * 文件观察类
 * 
 * @author mjk
 *
 */
public class FileObserver {
	
	public static void main(String[] args) {
		FileObserver observer = new FileObserver();
		observer.fileMonitor("D:\\project\\sync\\target",".xml", 5,new FileListener() {

            @Override
			public void onFileChange(File file) {
				BizLogger.info(file.getName());
			}
		});
	}
	/**
	 * 
	 * @param fileName 监听的文件目录
	 * @param time     每次监听的时间间隔
	 * @param listener 监听类
	 */
	public void fileMonitor(String fileName,String suffix, long time ,FileListener listener) {
		try {
			File directory = new File(fileName);
			// 创建一个文件观察器用于处理文件的格式
			// 创建过滤器
	        IOFileFilter directories = FileFilterUtils.and(
	                FileFilterUtils.directoryFileFilter(),
	                HiddenFileFilter.VISIBLE);
	        IOFileFilter files = FileFilterUtils.and(
	                FileFilterUtils.fileFileFilter(),
	                FileFilterUtils.suffixFileFilter(suffix));
	        IOFileFilter filter = FileFilterUtils.or(directories, files);
			FileAlterationObserver observer = new FileAlterationObserver(directory, filter);
			// 设置文件变化监听器
			observer.addListener(listener);
			FileAlterationMonitor monitor = new FileAlterationMonitor(TimeUnit.SECONDS.toMillis(5), observer);
			monitor.start();
		} catch (Exception e) {
			BizLogger.error(e);
		}
	}
	/**
	 * 文件监听类
	 * @author mjk
	 *
	 */
	public static class FileListener implements FileAlterationListener {
		@Override
		public void onStart(FileAlterationObserver fileAlterationObserver) {
			// Do nothing
		}
		@Override
		public void onDirectoryCreate(File file) {
			// Do nothing
		}
		@Override
		public void onDirectoryChange(File file) {
			// Do nothing
		}
		@Override
		public void onDirectoryDelete(File file) {
			// Do nothing
		}		
		@Override
		public void onStop(FileAlterationObserver fileAlterationObserver) {
			// Do nothing
		}
		@Override
		public void onFileCreate(File file) {
			// Do nothing
		}
		@Override
		public void onFileChange(File file) {
			// Do nothing
		}
		@Override
		public void onFileDelete(File file) {
			// Do nothing
		}
	}
}
